<template>
  <div class="Coupon_CreateIssue">
    <div>
      <!-- 搜索框 -->
      <el-form
        :model="queryForm"
        ref="queryForm"
        size="small"
        :inline="true"
        label-width="88px"
        style="margin-top: 8px"
        class="globalSerchFormStyle"
      >
        <el-row>
          <el-col :span="6" v-if="authUser">
            <el-form-item
              label="油企名称："
              prop="enterpriseId"
              size="small"
              style="padding-top: 4px"
            >
              <el-select
                v-model="queryForm.enterpriseId"
                :clearable="true"
                filterable
                placeholder="请选择油企"
                @change="handleSelectChange"
                style="width: 180px"
              >
                <el-option
                  v-for="(item, index) in enterpriseList"
                  :key="index"
                  :value="item.enterpriseId"
                  :label="item.enterpriseName"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="油站名称：" prop="stationName" clearable>
              <el-select
                v-model="queryForm.stationName"
                :clearable="true"
                filterable
                placeholder="请选择油站"
                style="width: 180px"
              >
                <el-option
                  v-for="(item, index) in stationList"
                  :key="index"
                  :label="item.stationName"
                  :value="item.stationName"
                >
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="活动名称：" prop="activityName">
              <el-input
                v-model="queryForm.activityName"
                placeholder="请输入活动名称"
                clearable
                style="width: 180px"
              />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="发放类型：" prop="issueType" v-if="!authUser">
              <el-select
                v-model="queryForm.issueType"
                clearable
                placeholder="请选择"
                style="width: 180px"
              >
                <el-option label="手动领取" value="0"></el-option>
                <el-option label="注册发放" value="5"></el-option>
                <el-option label="支付成功后发放" value="1"></el-option>
                <el-option label="Plus会员专用" value="2"></el-option>
                <el-option
                  label="数据预录入模板（给用户导入优惠券时使用）"
                  value="3"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row v-show="collapse">
          <el-col :span="6" v-if="authUser">
            <el-form-item label="发放类型：" prop="issueType">
              <el-select
                v-model="queryForm.issueType"
                clearable
                placeholder="请选择"
                style="width: 180px"
              >
                <el-option label="手动领取" value="0"></el-option>
                <el-option label="注册发放" value="5"></el-option>
                <el-option label="支付成功后发放" value="1"></el-option>
                <el-option label="Plus会员专用" value="2"></el-option>
                <el-option
                  label="数据预录入模板（给用户导入优惠券时使用）"
                  value="3"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="活动状态：" prop="activityStatus">
              <el-select
                v-model="queryForm.activityStatus"
                clearable
                placeholder="请选择"
                style="width: 180px"
              >
                <el-option label="未开始" value="0"></el-option>
                <el-option label="进行中" value="1"></el-option>
                <el-option label="已暂停" value="2"></el-option>
                <el-option label="已结束" value="3"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="创建时间：" prop="getCreateTime">
              <el-date-picker
                v-model="dateRangeCreatedDate"
                size="mini"
                value-format="yyyy-MM-dd HH:mm:ss"
                type="datetimerange"
                range-separator="至"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
                style="width: 180px"
              >
              </el-date-picker>
            </el-form-item>
          </el-col>
          <!-- <el-col :span="6"> -->
          <!-- <el-form-item
            label="参与用户："
            prop="status"
          >
            <el-select
              v-model="queryForm.status"
              clearable
              placeholder="请选择"
            >
              <el-option
                v-for="item in userPatList"
                :key="item.label"
                :label="item.label"
                :value="item.value"
              ></el-option>
            </el-select>
          </el-form-item> -->
          <!-- <el-form-item label="发放名称：" prop="issueName" class="pd4">
            <el-input v-model="queryForm.issueName" placeholder="请输入名称" clearable size="small" />
          </el-form-item> -->
          <!-- </el-col> -->
        </el-row>
      </el-form>

      <!-- 按钮组合 -->
      <el-row
        class="global_el_rowStyle"
        :gutter="10"
        style="
          border-top: none;
          border-bottom: 1px solid #f5f5f5;
          margin-top: 0px;
        "
      >
        <el-col :span="1.5">
          <el-button
            type="primary"
            icon="el-icon-search"
            size="mini"
            @click="handleQuery"
            >搜索</el-button
          >
        </el-col>
        <el-col :span="1.5">
          <el-button
            type="info"
            icon="el-icon-refresh"
            size="mini"
            @click="resetQuery"
            >重置</el-button
          >
        </el-col>
        <el-col :span="1.5">
          <el-button
            plain
            size="mini"
            id="closeSearchBtn"
            @click="
              (closeSearch) => {
                collapse = !collapse;
              }
            "
          >
            {{ collapse ? "收起" : "展开" }}
            <i
              :class="collapse ? 'el-icon-arrow-up ' : 'el-icon-arrow-down'"
            ></i>
          </el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button
            type="primary"
            icon="el-icon-plus"
            size="mini"
            @click="handleAdd"
            >新增</el-button
          >
        </el-col>
        <el-col :span="1.5">
          <el-button
            plain
            icon="el-icon-delete"
            size="mini"
            :disabled="selectedIds.length === 0"
            @click="deleteSelectedActivities"
            >删除</el-button
          >
        </el-col>
        <!-- <el-col :span="1.5">
          <el-button plain size="mini" @click="showSelfHexiao">
            优惠券自助核销
          </el-button>
        </el-col> -->
      </el-row>

      <!-- 表格 -->
      <el-table :data="issueList" @selection-change="handleSelectionChange">
        <!--
          <af-table-column type="expand">
            <template slot-scope="props">
              <el-table
                :data="props.row.couponList"
                :show-header="false"
                :highlight-current-row="false"
                style="width: 90vw"
              >
                <af-table-column label="名城" align="left">
                  <template slot-scope="scope">
                    {{ "优惠券：" }}<b>{{ scope.row.couponRemark }}</b>
                  </template>
                </af-table-column>
                <af-table-column label="卡片类型" align="left">
                  <template slot-scope="scope">
                    {{
                      scope.row.couponType == 1
                        ? "现金劵" + "--面值：" + scope.row.couponAmt + "元"
                        : ""
                    }}
                    {{
                      scope.row.couponType == 2
                        ? "折扣券" + "--折扣：" + scope.row.couponAmt + "% "
                        : ""
                    }}
                    {{
                      scope.row.couponType == 3
                        ? "兑换券" + "--商品：" + scope.row.couponName
                        : ""
                    }}
                  </template>
                </af-table-column>
                <af-table-column label="状态" align="left">
                  <template slot-scope="scope">
                    {{ scope.row.status == "1" ? "启用状态" : "" }}
                    {{ scope.row.status == "0" ? "停用状态" : "" }}
                  </template>
                </af-table-column>
              </el-table>
            </template>
          </af-table-column>
          -->
        <el-table-column type="selection" width="55" />

        <af-table-column
          label="油站名称"
          align="left"
          prop="stationName"
          show-overflow-tooltip
          width="200"
        />

        <!-- <af-table-column label="发放方式标识" align="left" prop="issueRemark" />
        <af-table-column label="状态" align="left">
          <template slot-scope="scope">
            <el-switch v-model="scope.row.status" active-value="1" inactive-value="0"
              @change="handleStatusChange(scope.row)"></el-switch>
          </template>
        </af-table-column> -->
        <af-table-column label="活动名称" align="left" prop="activityName" />
        <af-table-column label="活动ID" align="left" prop="id" />
        <af-table-column
          label="发放类型"
          align="left"
          width="150"
          prop="issueType"
        >
          <template slot-scope="scope">
            {{ scope.row.issueType == "0" ? "手动领取" : "" }}
            {{ scope.row.issueType == "1" ? "支付成功后发放" : "" }}
            {{ scope.row.issueType == "2" ? "Plus会员" : "" }}
            {{ scope.row.issueType == "3" ? "数据预录" : "" }}
            {{ scope.row.issueType == "5" ? "注册发放" : "" }}
            {{ scope.row.issueType == "6" ? "推荐成功后发放" : "" }}
          </template>
        </af-table-column>

        <af-table-column
          label="参与活动车主"
          align="left"
          width="200"
          prop="id"
        >
          <template slot-scope="scope">
            {{
              scope.row.memberLevelList
                ? scope.row.memberLevelList.includes("1")
                  ? "普卡，"
                  : ""
                : ""
            }}
            {{
              scope.row.memberLevelList
                ? scope.row.memberLevelList.includes("2")
                  ? "银卡，"
                  : ""
                : ""
            }}
            {{
              scope.row.memberLevelList
                ? scope.row.memberLevelList.includes("3")
                  ? "金卡，"
                  : ""
                : ""
            }}
            {{
              scope.row.memberLevelList
                ? scope.row.memberLevelList.includes("4")
                  ? "钻卡，"
                  : ""
                : ""
            }}
            {{
              scope.row.memberLevelList
                ? scope.row.memberLevelList.includes("5")
                  ? "黑卡，"
                  : ""
                : ""
            }}
            {{
              scope.row.memberLevelList
                ? scope.row.memberLevelList.includes("6")
                  ? "超级会员-月卡，"
                  : ""
                : ""
            }}
            {{
              scope.row.memberLevelList
                ? scope.row.memberLevelList.includes("7")
                  ? "超级会员-季卡，"
                  : ""
                : ""
            }}
            {{
              scope.row.memberLevelList
                ? scope.row.memberLevelList.includes("8")
                  ? "超级会员-年卡，"
                  : ""
                : ""
            }}
          </template>
        </af-table-column>

        <el-table-column label="活动状态" prop="activityStatus">
          <template slot-scope="scope">
            {{ getActivityStatusText(scope.row.activityStatus) }}
          </template>
        </el-table-column>
        <af-table-column
          label="活动开始时间"
          align="left"
          prop="activityStartTime"
        />
        <af-table-column
          label="活动结束时间"
          align="left"
          prop="activityEndTime"
        />
        <af-table-column label="创建时间" align="left" prop="createTime" />
        <af-table-column label="附件" align="left">
          <template slot-scope="scope">
            <!-- {{
              scope.row.issueType == "0"
              ? "-------"
              : ""
            }}
            {{ scope.row.issueType == "5"
              ? "导入码：" + scope.row.id
              : "" }} -->
            <el-button
              size="mini"
              type="text"
              icon="el-icon-download"
              @click="handleExport(scope.row)"
              v-if="scope.row.issueType == '0'"
              >导出二维码、网址</el-button
            >
          </template>
        </af-table-column>
        <!--
          <af-table-column label="发放门槛" align="left">
            <template slot-scope="scope">
              {{
                (scope.row.issueType == "1" || scope.row.issueType == "3")
                  ? (scope.row.getThresholdAmt == "0" ? "无门槛，消费都发放" : "满") + scope.row.getThresholdAmt + "元" + (scope.row.issueType == "1" ? "发放": "") + (scope.row.issueType == "3" ? "触发": "")
                  : ""
              }}
              {{ !(scope.row.issueType == "1" || scope.row.issueType == "3") ? "-------" : "" }}

            </template>
          </af-table-column>
          <af-table-column label="领取限制" align="left">
            <template slot-scope="scope">
              {{ scope.row.issueType == "1" ? "-------" : "" }}
              {{ scope.row.issueType == "4" ? "-------" : "" }}
              {{
                (scope.row.issueType == "2"||scope.row.issueType == "3")
                  ? "单个用户能进入这个领取界面" +
                    scope.row.giveCount +
                    "次，一次可以领取" +
                    scope.row.giveLimit +
                    "张优惠券"
                  : ""
              }}
            </template>
          </af-table-column>
          <af-table-column label="可领取时间段" align="left">
            <template slot-scope="scope">
              {{scope.row.issueType == "4" ? "-------":"" }}
              {{ scope.row.issueType == "1" || scope.row.issueType == "2" || scope.row.issueType == "3" ? translateTime(scope.row) : "" }}
            </template>
          </af-table-column>
          -->
        <af-table-column
          label="操作"
          align="left"
          class-name="small-padding fixed-width"
        >
          <template slot-scope="scope">
            <el-button
              size="mini"
              type="text"
              icon="el-icon-edit"
              @click="handleView(scope.row)"
              >查看</el-button
            >
            <el-button
              size="mini"
              type="text"
              :disabled="scope.row.activityStatus !== '0'"
              @click="handleEdit(scope.row)"
              >编辑</el-button
            >
            <el-button
              size="mini"
              type="text"
              @click="handleStatuUpdate(scope.row)"
            >
              {{ getStatusText(scope.row.activityStatus) }}
            </el-button>
            <el-button size="mini" type="text" @click="handleCopy(scope.row)"
              >复制模版</el-button
            >
          </template>
        </af-table-column>
      </el-table>
      <pagination
        :hidden="total > 0 ? false : true"
        :total="total"
        :page.sync="queryForm.pageNum"
        :limit.sync="queryForm.pageSize"
        @pagination="getIssueList"
        :autoScroll="true"
      />
    </div>

    <!-- 添加或修改油站设备管理对话框 -->
    <el-dialog
      :title="title"
      :visible.sync="open"
      width="600px"
      append-to-body
      status-icon
    >
      <el-form
        ref="dialogForm"
        :model="createForm"
        :rules="rules"
        label-width="180px"
      >
        <el-form-item
          label="发放标识(给油站备注)"
          prop="issueRemark"
          :rules="{
            required: true,
            message: '请填入方案方式标识',
            trigger: 'blur',
          }"
        >
          <input
            type="text"
            class="form-control"
            v-model="createForm.issueRemark"
            style="width: 180px"
          />
        </el-form-item>
        <el-form-item
          label="活动名称(给用户展示)"
          prop="issueName"
          :rules="{
            required: true,
            message: '请填入活动名称',
            trigger: 'blur',
          }"
        >
          <input
            type="text"
            class="form-control"
            v-model="createForm.issueName"
            style="width: 180px"
          />
        </el-form-item>
        <el-form-item
          label="发放类型"
          prop="issueType"
          :rules="{
            required: true,
            message: '请选择发放类型',
            trigger: 'change',
          }"
        >
          <el-radio-group v-model="createForm.issueType">
            <div>
              <el-radio label="1">消费发放</el-radio>
            </div>
            <div>
              <el-radio label="2">网页方式、二维码-静态码</el-radio>
            </div>
            <div>
              <el-radio label="3">支付成功后的领取位(只能设置一次)</el-radio>
            </div>
            <div>
              <el-radio label="4">数据预录入模板</el-radio>
            </div>
          </el-radio-group>
        </el-form-item>
        <el-form-item
          label="能进入的次数"
          prop="giveCount"
          v-if="createForm.issueType == 2 || createForm.issueType == 3"
          :rules="{
            required: createForm.issueType == 2 || createForm.issueType == 3,
            message: '请填入能进入的次数',
            trigger: 'blur',
          }"
        >
          单个用户能进入这个领取界面
          <input
            type="text"
            class="form-control d-inline-block"
            v-model.number="createForm.giveCount"
            style="width: 80px"
          />
          次
        </el-form-item>

        <el-form-item
          label="一次能领取几张次数"
          prop="giveLimit"
          v-if="createForm.issueType == 2 || createForm.issueType == 3"
          :rules="{
            required: createForm.issueType == 2 || createForm.issueType == 3,
            message: '请填入一次能领取几张次数',
            trigger: 'blur',
          }"
        >
          用户进入后一次能领取<input
            type="text"
            class="form-control d-inline-block"
            v-model.number="createForm.giveLimit"
            style="width: 80px"
          />张
        </el-form-item>
        <el-form-item
          label="发放门槛"
          prop="discountThresholdAmt"
          v-if="createForm.issueType == 1 || createForm.issueType == 3"
        >
          消费达到
          <input
            type="text"
            class="form-control d-inline-block"
            v-model.number="createForm.discountThresholdAmt"
            style="width: 80px"
          />元时，{{ createForm.issueType == 1 ? "系统自动发放" : ""
          }}{{ createForm.issueType == 3 ? "触发领取页" : "" }}
        </el-form-item>
        <el-form-item
          label="可领取时间段"
          prop="availableControl"
          v-if="
            this.createForm.issueType == 1 ||
            this.createForm.issueType == 2 ||
            this.createForm.issueType == 3
          "
          :rules="[
            {
              required: this.availableControlRequired,
              message: '请选择有效期内时间控制',
              trigger: 'change',
            },
            {
              validator: this.validateAvailableControl,
              trigger: 'change',
            },
          ]"
        >
          <div>
            <el-radio-group
              v-model="createForm.availableControl"
              @change="availableControlChange"
            >
              <div>
                <div>
                  <el-radio label="0">一直都可用</el-radio>
                  <el-radio label="1">每周指定日</el-radio>
                </div>
                <div>
                  <el-radio label="2">每月指定日</el-radio>
                  <el-radio label="3">固定指定日</el-radio>
                </div>
              </div>
            </el-radio-group>
          </div>
          <div
            v-if="
              createForm.availableControl == 1 ||
              createForm.availableControl == 2 ||
              createForm.availableControl == 3
            "
            style="margin-top: 10px"
          >
            <select-day
              :type="createForm.availableControl"
              :day.sync="createForm.appointedDaysList"
              :cycle.sync="createForm.cycleDaysList"
            >
            </select-day>
          </div>
        </el-form-item>
        <el-form-item
          label="此领取方式下的优惠券"
          prop="couponIssueRelationList"
        >
          （用于用户领取）
        </el-form-item>

        <div>
          <el-col :span="11">
            <el-table
              :data="unselectedCouponList"
              border
              size="mini"
              :resizable="false"
              highlight-current-row
              height="500"
              @selection-change="handleLeftChange"
              disabled
              ref="leftTable"
            >
              >
              <el-table-column label="可选">
                <el-table-column
                  prop="phone"
                  label="姓名"
                  type="selection"
                ></el-table-column>
                <el-table-column
                  prop="couponRemark"
                  label="优惠券"
                ></el-table-column>
                <el-table-column label="添加" width="60px" align="left">
                  <template slot-scope="scope">
                    <el-button
                      type="text"
                      icon="el-icon-circle-plus-outline"
                      class="underline btn24"
                      size="mini"
                      @click="handleMoveLabel('right', scope.row)"
                      >添加</el-button
                    >
                  </template>
                </el-table-column>
              </el-table-column>
            </el-table>
          </el-col>
          <el-col :span="2" style="text-align: center">
            <el-button
              type="primary"
              size="mini"
              @click="toggleLabel"
              style="
                margin-top: 200px;
                text-align: center;
                width: 30px;
                padding-right: 0;
                padding-left: 0;
              "
              :disabled="toggleable"
              >切换</el-button
            >
          </el-col>
          <el-col :span="11">
            <el-table
              :data="selectedCouponList"
              border
              size="mini"
              highlight-current-row
              :resizable="false"
              height="500"
              @selection-change="handleRightChange"
              :loading="true"
              ref="rightTable"
            >
              <el-table-column label="已选" :resizable="false">
                <el-table-column
                  prop="phone"
                  type="selection"
                ></el-table-column>
                <el-table-column
                  prop="couponRemark"
                  label="优惠券"
                ></el-table-column>
                <el-table-column label="移除" width="60px" align="left">
                  <template slot-scope="scope">
                    <el-button
                      type="text"
                      icon="el-icon-remove-outline"
                      class="underline btn24"
                      size="mini"
                      @click="handleMoveLabel('left', scope.row)"
                      >移除</el-button
                    >
                  </template>
                </el-table-column>
              </el-table-column>
            </el-table>
          </el-col>
        </div>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <el-dialog
      :visible.sync="exportQrDialog"
      width="600px"
      append-to-body
      title="导出发放方式"
    >
      <div>
        <qr
          :text="currentExport.text"
          @downloadImg="downloadImg"
          :name="currentExport.name + '活动二维码'"
        >
          <div>{{ currentExport.name }} 活动二维码<b></b></div>
        </qr>
        <!--
        <div
          style="text-align: center; margin-top: 15px"
          v-clipboard:copy="currentExport.text"
          v-clipboard:error="onCopyError"
          v-clipboard:success="onCopySuccess"
        >
          👇点击复制网址👇
        </div>
        -->
        <div
          style="text-align: center; margin-top: 15px"
          v-clipboard:copy="currentExport.text"
          v-clipboard:error="onCopyError"
          v-clipboard:success="onCopySuccess"
        >
          活动网址：{{ currentExport.text }}
        </div>
        <div
          style="text-align: center"
          v-clipboard:copy="currentExport.text"
          v-clipboard:error="onCopyError"
          v-clipboard:success="onCopySuccess"
        >
          👆点击复制网址👆
        </div>
      </div>
    </el-dialog>

    <!-- 自助优惠券核销 -->
    <CouponHeXiaoSelf
      :hexiaoSelfDialog.sync="hexiaoSelfDialog"
      :text="hexiaoSelfText"
    >
    </CouponHeXiaoSelf>
  </div>
</template>

<script>
import Vue from "vue";
import VueClipboard from "vue-clipboard2";
import Qr from "@/components/QrCode/coupon-qr.vue";
import Base64 from "@/utils/base64";
import CouponHeXiaoSelf from "./Coupon_HeXiao_self";

Vue.use(VueClipboard);

import {
  listInfo,
  changeCouponStatus,
  addIssue,
  listIssue,
  upIssueStatus,
  deleteCouponActivity,
  getCouponActivity,
  getAllCouponActivities,
  updateActivityStatus,
  deleteCouponActivityByIds,
} from "@/api/coupon";
import SelectDay from "@/components/SelectDay";
import settings from "@/settings";
import { enterpriseList } from "@/api/station/orderHistory";
import { listEnterpriseStation } from "@/api/dept";

export default {
  name: "Coupon_CreateIssue",
  components: {
    SelectDay: SelectDay,
    Qr: Qr,
    VueClipboard: VueClipboard,
    CouponHeXiaoSelf,
  },
  data() {
    let validateAvailableControl = (rule, value, callback) => {
      if (this.createForm.availableControl == 4) {
      }
      if (
        this.createForm.availableControl == 1 ||
        this.createForm.availableControl == 2
      ) {
        if (this.createForm.cycleDaysList.length == 0) {
          callback(new Error("请选择时间"));
          return;
        }
      }
      if (this.createForm.availableControl == 3) {
        if (this.createForm.appointedDaysList.length == 0) {
          callback(new Error("请选择日期"));
          return;
        }
      }
      callback();
    };
    let validateCouponIssueRelationList = (rule, value, callback) => {
      if (this.createForm.couponIssueRelationList.length == 0) {
        callback(new Error("请选择优惠券"));
      }
      callback();
    };
    return {
      getStatusText(status) {
        if (status === "0") {
          return "启动";
        } else if (status === "1") {
          return "停止";
        } else if (status === "2") {
          return "启动";
        } else {
          return "";
        }
      },
      activityStatusOptions: [
        { label: "未开始", value: "0" },
        { label: "进行中", value: "1" },
        { label: "已暂停", value: "2" },
        { label: "已结束", value: "3" },
      ],
      selectedIds: [], // 用于存储选中的优惠券活动的 ids
      collapse: false,
      dateRangeCreatedDate: [],
      couponEnabledFlag: "1",
      exportQrDialog: false,
      createForm: {
        issueRemark: "",
        issueName: "",
        showIdList: [],
        availableControl: "0",
        appointedDaysList: [],
        cycleDaysList: [],
        issueType: "",
        discountThresholdAmt: "0",
        couponIssueRelationList: [],
        giveLimit: 9,
        giveCount: 999999,
      },
      currentExport: {
        text: "error",
        type: "你好",
        name: "二维码",
      },
      couponList: [],
      oilNameList: [],
      allVerificationList: [],
      equipmentList: [],
      // 油枪复选
      allGunList: [],
      // 已选的油枪
      checkedGunList: [],
      //设备状态
      deviceStatusOptions: [],
      //设备类型
      deviceTypeOptions: [],
      stationOptions: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 总条数
      total: 100,
      leftQuery: {},
      rightQuery: {},
      leftData: [],
      rightData: [],
      moveRightData: [],
      moveLeftData: [],
      // 查询参数
      queryForm: {
        pageNum: 1,
        pageSize: 10, // 初始值只能比10大
        enterpriseId: null,
        activityName: null,
        activityStatus: null,
        stationName: null,
      },
      // 表单校验
      rules: {
        availableControl: [
          // {
          //   required: this.availableControlRequired,
          //   message: "请选择有效期内时间控制",
          //   trigger: "change",
          // },
          { validator: validateAvailableControl, trigger: "change" },
        ],
        couponIssueRelationList: [
          {
            required: true,
            message: "请选择优惠券",
            trigger: "change",
          },
          { validator: validateCouponIssueRelationList, trigger: "change" },
        ],
      },
      day: [],
      cycle: [],
      issueList: [],
      timeSelect: [
        ,
        ["周天", "周一", "周二", "周三", "周四", "周五", "周六"],
        [
          "1号",
          "2号",
          "3号",
          "4号",
          "5号",
          "6号",
          "7号",
          "8号",
          "9号",
          "10号",
          "11号",
          "12号",
          "13号",
          "14号",
          "15号",
          "16号",
          "17号",
          "18号",
          "19号",
          "20号",
          "21号",
          "22号",
          "23号",
          "24号",
          "25号",
          "26号",
          "27号",
          "28号",
          "29号",
          "30号",
          "31号",
        ],
      ],
      enterpriseList: [],
      stationList: [],
      userPatList: [
        {
          label: "普卡",
          value: "",
        },
        {
          label: "银卡",
          value: "",
        },
        {
          label: "金卡",
          value: "",
        },
        {
          label: "钻卡",
          value: "",
        },
        {
          label: "黑卡",
          value: "",
        },
        {
          label: "微信",
          value: "",
        },
        {
          label: "支付宝",
          value: "",
        },
        {
          label: "老用户",
          value: "",
        },
        {
          label: "新用户",
          value: "",
        },
      ],

      hexiaoSelfDialog: false, // 自助核销优惠券抽屉
      hexiaoSelfText: "3333", // 优惠券核销二维码参数文本
    };
  },
  filters: {
    toFixed: function (value) {
      if (value == 0) {
        return 0;
      }
      return (+value).toFixed(2);
    },
  },

  created() {
    this.init();
    this.getStationList();
  },
  computed: {
    authUser() {
      let roles = this.$store.state.user.roles;
      if (roles.includes("admin")) {
        return true;
      } else {
        return false;
      }
    },
    availableControlRequired() {
      // this.rules = { ...this.rules };
      return (
        this.createForm.issueType == 1 ||
        this.createForm.issueType == 2 ||
        this.createForm.issueType == 3
      );
    },
    toggleable() {
      if (this.moveRightData.length === 0 && this.moveLeftData.length === 0) {
        return true;
      }
      return false;
    },
    selectedCouponList() {
      return this.couponList.filter((ele) => {
        if (this.createForm.couponIssueRelationList == null) {
          this.createForm.couponIssueRelationList = [];
        }
        return this.createForm.couponIssueRelationList.includes(ele.id);
      });
    },
    unselectedCouponList() {
      return this.couponList.filter((ele) => {
        if (this.createForm.couponIssueRelationList == null) {
          this.createForm.couponIssueRelationList = [];
        }
        return !!!this.createForm.couponIssueRelationList.includes(ele.id);
      });
    },
    getTodayDateString() {
      const date = new Date();
      let y = date.getFullYear();
      let m = date.getMonth().toString();
      let s = date.getDate().toString();
      m = "" + (m.length == 1 ? "0" : "") + m;
      s = "" + (s.length == 1 ? "0" : "") + s;
      return "" + y + ":" + m + ":" + s;
    },
  },
  methods: {
    async handleStatuUpdate(row) {
      try {
        let newStatus;

        // 根据当前状态确定新的状态值
        if (row.activityStatus === "0") {
          newStatus = "1"; // 如果当前状态为 '0'，则将新状态设置为 '1'（停用变为启用）
        } else if (row.activityStatus === "1") {
          newStatus = "2"; // 如果当前状态为 '1'，则将新状态设置为 '2'（启用变为停用）
        } else if (row.activityStatus === "2") {
          newStatus = "1"; // 如果当前状态为 '2'，则将新状态设置为 '1'（停用变为启用）
        } else {
          console.error("无效的状态值:", row.status);
          return;
        }

        // 调用 API 更新优惠券状态
        await updateActivityStatus(row.id, newStatus);

        // 更新表格行中的状态值
        row.activityStatus = newStatus;

        // 提示用户操作成功
        this.$message.success("优惠券状态更新成功。");
      } catch (error) {
        console.error("优惠券状态更新失败:", error);
        this.$message.error("优惠券状态更新失败，请重试。");
      }
    },
    getActivityStatusText(activityStatus) {
      const statusOption = this.activityStatusOptions.find(
        (option) => option.value === activityStatus
      );
      return statusOption ? statusOption.label : "未知状态";
    },
    // 当用户选中/取消选中某个优惠券活动时调用
    handleSelectionChange(selection) {
      this.selectedIds = selection.map((item) => item.id);
    },
    // 点击删除按钮时调用
    deleteSelectedActivities() {
      if (this.selectedIds.length > 0) {
        this.$confirm("是否确认删除选中的优惠券活动?", "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        })
          .then(() => {
            // 用户点击了确认按钮，执行删除操作
            return deleteCouponActivityByIds(this.selectedIds);
          })
          .then((response) => {
            // 删除操作成功的处理
            this.init();
            this.$message.success("优惠券活动删除成功");
          })
          .catch((error) => {
            // 取消或删除操作失败的处理
            this.init();
          });
      }
    },

    // 优惠券自助核销
    showSelfHexiao() {
      this.hexiaoSelfDialog = true;
    },

    // 查询油企
    getEnterpriseList() {
      enterpriseList().then((res) => {
        this.enterpriseList = res.rows;
      });
    },
    // 查询油站
    getStationList(val) {
      listEnterpriseStation({ enterpriseId: val }).then((res) => {
        this.stationList = res;
        const allStations = {
          stationId: "all",
          stationName: "全部油站",
        };
        if (this.$store.state.user.userLevel != "2") {
          this.stationList.push(allStations);
        }
      });
    },
    // 选择油企
    handleSelectChange(val) {
      this.stationList = [];
      this.queryForm.stationId = null;
      this.getStationList(val);
    },
    validateAvailableControl(rule, value, callback) {
      if (this.createForm.issueType == 4) {
        callback();
      }

      if (
        this.createForm.availableControl == 1 ||
        this.createForm.availableControl == 2
      ) {
        if (this.createForm.cycleDaysList.length == 0) {
          callback(new Error("请选择时间"));
          return;
        }
      }
      if (this.createForm.availableControl == 3) {
        if (this.createForm.appointedDaysList.length == 0) {
          callback(new Error("请选择日期"));
          return;
        }
      }
      callback();
    },
    onCopySuccess() {
      this.msgSuccess("网址已经拷贝到剪切板");
    },
    onCopyError() {
      this.msgError("网址拷贝失败，请手动复制");
    },
    handleExport(row) {
      let url = window.location.origin;
      let baseURL = "";
      switch (url) {
        case "https://yftx.xailife.com":
          baseURL = settings.baseURL;
          break;
        case "https://yftx-test.xailife.com":
          baseURL = settings.baseTestURL;
          break;
        case "https://yftx-test.xailife.com":
          baseURL = settings.baseDevURL;
          break;
        default:
          baseURL = settings.baseDevURL;
          break;
      }
      this.currentExport.name = row.activityName;
      const base64 = Base64.getInstance();
      const encodeStr = "i" + row.id;
      console.log(encodeStr);
      const encodedStr = base64.encode(encodeStr);
      const trimEqualStr = encodedStr.replace(/={1,}$/g, "");
      this.exportQrDialog = true;
      this.currentExport.text =
        // settings.baseURL + '/' + this.presentEnterprise.enterpriseId + "/" + trimEqualStr;
        `${baseURL}/${this.presentEnterprise.enterpriseId}/${trimEqualStr}`;
    },
    downloadImg() {},
    translateTime(row) {
      let timeString = "";
      //  console.log( row.startDate);
      //   const availableControleType = row.availableControl;
      //   if (availableControleType == 0) {
      //     return "用户一直都可以领取";
      //   }
      //   timeString = "用户只能在";
      //   if (availableControleType == 1) {
      //     timeString += "每周的";
      //   }
      //   if (availableControleType == 2) {
      //     timeString += "每月的";
      //   }
      //   if (availableControleType == 3) {
      //     timeString += "指定的日期 ";
      //   }
      //   if (availableControleType == 1 || availableControleType == 2) {
      //     row.cycleDaysList.forEach((ele) => {
      //       timeString += this.timeSelect[availableControleType][ele] + "、";
      //     });
      //   } else if (availableControleType == 3) {
      //     timeString += row.appointedDaysList.toString();
      //   }

      timeString =
        "开始：" + row.startDate + "截至：" + row.endDate + "可以领取劵";
      return timeString;
    },
    getIssueList() {
      if (
        this.dateRangeCreatedDate !== null &&
        this.dateRangeCreatedDate.length >= 2
      ) {
        const [startTime, endTime] = this.dateRangeCreatedDate;

        // 更新 queryForm 的 startTime 和 endTime 字段
        this.queryForm.startTime = startTime;
        this.queryForm.endTime = endTime;

        // 继续处理其他逻辑
      }
      if (
        this.$store.state.user.userLevel === "2" &&
        this.$store.state.user.presentStationName
      ) {
        this.queryForm.stationName = this.$store.state.user.presentStationName;
      }
      getAllCouponActivities(this.queryForm)
        .then((res) => {
          if (res.code == 200) {
            if (res.rows == null) {
              this.total = 0;
              this.issueList = [];
            } else {
              this.total = res.total;
              this.issueList = res.rows;
            }
          } else {
            throw new Error("");
          }
        })
        .catch((err) => {
          this.msgError("亲，拉取领取方式列表失败~");
        });
    },

    getCoupon() {
      listInfo({
        pageNum: 1,
        pageSize: 1000,
        status: 1,
      })
        .then((res) => {
          if (res.code == 200) {
            if (res.rows == null) {
              this.couponList = [];
            } else {
              this.couponList = res.rows;
            }
          } else {
            throw new Error("");
          }
        })
        .catch((err) => {
          this.msgError("亲，拉取优惠券列表失败~");
        });
    },
    availableControlChange() {
      this.createForm.appointedDaysList = [];
      this.createForm.cycleDaysList = [];
      this.createForm = { ...this.createForm };
    },
    handleMoveLabel(direction, row) {
      if (this.createForm.couponIssueRelationList == null) {
        this.createForm.couponIssueRelationList = [];
      }

      if (direction == "right") {
        this.createForm.couponIssueRelationList.push(row.id);
      } else {
        this.createForm.couponIssueRelationList =
          this.createForm.couponIssueRelationList.filter((ele) => {
            return ele != row.id;
          });
      }
    },
    handleFlagChange() {
      const that = this;
      let text = this.couponEnabledFlag === "1" ? "启用" : "停用";
      this.$confirm('确认要"' + text + '"优惠券功能吗?', "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(function () {
          return changeCouponStatus({
            deptId: that.deptId,
            couponEnabledFlag: that.couponEnabledFlag,
          });
        })
        .then(() => {
          that.msgSuccess(text + "成功");
        })
        .catch(function () {
          that.couponEnabledFlag = that.couponEnabledFlag === "0" ? "1" : "0";
        });
    },
    handleStatusChange(row) {
      let text = row.status === "1" ? "启用" : "停用";
      this.$confirm(
        '确认要"' + text + '""' + row.issueName + '"发放方式吗?',
        "警告",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }
      )
        .then(function () {
          return upIssueStatus({
            id: row.id,
            status: row.status,
          });
        })
        .then(() => {
          this.msgSuccess(text + "成功");
        })
        .catch(function () {
          row.status = row.status === "0" ? "1" : "0";
        });
    },
    toggleLabel() {
      if (this.moveLeftData.length !== 0) {
        this.createForm.couponIssueRelationList =
          this.createForm.couponIssueRelationList.filter((ele) => {
            return ele != this.moveLeftData;
          });
        this.createForm = { ...this.createForm };
        return;
      }
      if (this.moveRightData.length !== 0) {
        this.createForm.couponIssueRelationList = [
          ...new Set(
            this.createForm.couponIssueRelationList.concat(this.moveRightData)
          ),
        ].filter((ele) => {
          return !!ele;
        });
        this.createForm = { ...this.createForm };
        return;
      }
      return;
    },
    handleLeftChange(val) {
      let changeArr = [];
      val.map((ele) => {
        changeArr.push(ele.id);
      });
      this.moveLeftData = [];
      this.moveRightData = changeArr;
      this.$refs.rightTable.clearSelection();
    },
    handleRightChange(val) {
      let changeArr = [];
      val.map((ele) => {
        changeArr.push(ele.id);
      });
      this.moveLeftData = changeArr;
      this.moveRightData = [];
      this.$refs.leftTable.clearSelection();
    },
    init() {
      // this.getOilList();
      let userLevel = this.$store.state.user.userLevel;
      if (userLevel === 1) {
        this.getStationList(
          this.$store.state.user.presentEnterprise.enterpriseId
        );
      }

      this.getCoupon();
      // this.getVerificationList();
      this.getIssueList();
    },
    // 取消按钮
    cancel() {
      this.open = false;
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryForm.pageNum = 1;
      this.queryForm.pageSize = 10;
      this.getIssueList();
    },
    deviceNoInput(value) {
      this.dialogForm.posQueue = value;
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.dateRangeCreatedDate = [];
      this.handleQuery();
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.$router.push({
        path: "/market/coupon/Coupon_CreateIssue_Edit",
        query: { isEdit: true, isState: "0" },
      });
      // this.createForm = {
      //   issueRemark: "",
      //   issueName: "",
      //   showIdList: [],
      //   availableControl: "0",
      //   appointedDaysList: [],
      //   cycleDaysList: [],
      //   issueType: "",
      //   discountThresholdAmt: "0",
      //   couponIssueRelationList: [],
      //   giveLimit: 9,
      //   giveCount: 999999,
      // };
      // this.title = "添加优惠券";

      // this.open = true;
    },
    // 编辑
    handleEdit(row) {
      this.$router.push({
        path: "/market/coupon/Coupon_CreateIssue_Edit",
        query: { id: row.id, isEdit: true, isCopy: false, isState: "2" },
      });
    },
    // 复制模板
    handleCopy(row) {
      this.$router.push({
        path: "/market/coupon/Coupon_CreateIssue_Edit",
        query: { id: row.id, isEdit: true, isState: "3" },
      });
    },
    /** 查看按钮操作 */
    handleView(row) {
      this.$router.push({
        path: "/market/coupon/Coupon_CreateIssue_Edit",
        query: { id: row.id, isEdit: false, isState: "1" },
      });
    },

    /** 提交按钮 */
    submitForm() {
      this.$refs["dialogForm"].validate((valid) => {
        if (valid) {
          if (!!this.createForm.id) {
            updateIssue(this.createForm)
              .then((res) => {
                if (res.code == 200) {
                  this.msgSuccess("亲，修改成功了~");
                  this.getIssueList();
                  this.open = false;
                } else {
                  throw new Error("");
                }
              })
              .catch((err) => {
                this.msgError("修改失败了呀~");
              });
          } else {
            addIssue(this.createForm)
              .then((res) => {
                if (res.code == 200) {
                  this.msgSuccess("亲，新增成功了~");
                  this.getIssueList();
                  this.open = false;
                } else {
                  throw new Error("");
                }
              })
              .catch((err) => {
                this.msgError("创建失败了~");
              });
          }
        }
      });
    },

    /** 删除按钮操作 */
    handleDelete(row) {
      const deviceIds = row.deviceId;
      this.$confirm("是否确认删除油站设备管理", "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(function () {
          return;
        })
        .then(() => {
          this.getList();
          this.msgSuccess("删除成功");
        });
    },
  },
};
</script>
<style lang="scss">
.Coupon_CreateIssue {
  padding: 0 20px;
}
</style>
